package com.yanxp.mybatis;

import com.yanxp.mybatis.build.SqlSessionFactoryBuild;
import com.yanxp.mybatis.config.Configuration;
import com.yanxp.mybatis.entity.User;
import com.yanxp.mybatis.factory.SqlSessionFactory;
import com.yanxp.mybatis.session.SqlSession;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * Hello world!
 */
public class App {

    public static void main(String[] args) throws Exception {
//        new App().test();
        SqlSession sqlSession = new SqlSessionFactoryBuild().build("/mybatis-config.xml").openSession();
        List<User> users = sqlSession.selectList("com.yanxp.mybatis.mapper.UserMapper","selectList");
        System.out.println(users);
        User param = new User();
        param.setUsername("2");
        param.setId(2L);
        User user = sqlSession.selectOne("com.yanxp.mybatis.mapper.UserMapper","selectOne",param);
        System.out.println(user);
    }

    public void test() throws Exception {
        //Dom4j 解析
        Configuration configuration = new Configuration();
        InputStream in = this.getClass().getResourceAsStream("/mapper/UserMapper.xml");
        SAXReader reader = new SAXReader();
        Document document = reader.read(in);
        Element root = document.getRootElement();
        List<Element> propertys = root.element("environments").element("environment")
                .element("dataSource").elements("property");
        propertys.stream().forEach(e -> {
            Attribute name = e.attribute("name");
            Attribute value = e.attribute("value");
            if ("driver".equals(name.getValue())) {
                configuration.setDriver(value.getValue());
            } else if ("url".equals(name.getValue())) {
                configuration.setUrl(value.getValue());
            } else if ("username".equals(name.getValue())) {
                configuration.setUsername(value.getValue());
            } else if ("password".equals(name.getValue())) {
                configuration.setPassword(value.getValue());
            }
        });
    }
}
